package com.alex.xmlyfm.adapters;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alex.mylibrary.cache.FileCache;
import com.alex.xmlyfm.Constants;
import com.alex.xmlyfm.R;
import com.alex.xmlyfm.entities.discoverrecommend.AlbumRecommend;
import com.alex.xmlyfm.entities.discoverrecommend.DiscoverRecommendAlbums;
import com.alex.xmlyfm.entities.discoverrecommend.DiscoverRecommendColumns;
import com.alex.xmlyfm.entities.discoverrecommend.DiscoverRecommendItem;
import com.alex.xmlyfm.entities.discoverrecommend.DiscoverRecommendSpecial;
import com.alex.xmlyfm.entities.discoverrecommend.SpecialItem;
import com.alex.xmlyfm.widgets.SpecialItemView;
import com.squareup.picasso.Picasso;

import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by
 * Author: alex
 * Email:
 * Date: 15-10-21.
 */

/**
 * 发现推荐部分的 ListView Adapter
 * 支持多布局的复用
 */
public class DiscoverRecommendAdapter extends BaseAdapter {

    private Context context;
    private List<DiscoverRecommendItem> items;

    // ---------------------------------
    //点击事件处理

    /**
     * 推荐专辑的点击事件
     */
    private View.OnClickListener onRecommendAlbumClickListener;

    public void setOnRecommendAlbumClickListener(View.OnClickListener onRecommendAlbumClickListener) {
        this.onRecommendAlbumClickListener = onRecommendAlbumClickListener;
    }








//---------------------------------


    public DiscoverRecommendAdapter(Context context, List<DiscoverRecommendItem> items) {
        this.context = context;
        this.items = items;
    }


    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public int getViewTypeCount() {
        return 3; //当前 ListView 可以显示三种类型 小编推荐中有   热门推荐，精品清单，发现新奇
    }

    @Override
    public int getItemViewType(int position) {
        int ret = 0;
        DiscoverRecommendItem item = items.get(position);

        if (item instanceof DiscoverRecommendAlbums){ // 小编推荐
            ret = 0;
        }else if (item instanceof DiscoverRecommendColumns){
            ret = 1;
        }else if (item instanceof DiscoverRecommendSpecial){
            ret = 2;
        }
        return ret;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View ret = null;

        // 1.获取数据
        DiscoverRecommendItem item = items.get(position);

        if (item instanceof DiscoverRecommendAlbums){ // 小编推荐
            ret = bindAlbumsView(position,convertView,parent);
        }else if (item instanceof DiscoverRecommendColumns){
            ret = bindColunmView(position,convertView,parent);
        }else if (item instanceof DiscoverRecommendSpecial){
            ret = bindSpecialView(position,convertView,parent);
        }



        return ret;
    }



    /**
     * 加载专辑推荐的 Item 小编推荐 热门推荐
     * @param position
     * @param convertView
     * @param parent
     */
    private View bindAlbumsView(int position, View convertView,ViewGroup parent){
        View ret = null;
        if (convertView != null) {
            ret = convertView;
        }else{
            LayoutInflater inflater = LayoutInflater.from(context);
            ret = inflater.inflate(R.layout.discover_recommend_altum_item,parent,false);
        }

        // ViewHolder
        AlbumViewHolder holder = (AlbumViewHolder) ret.getTag();

        if (holder == null){
            holder = new AlbumViewHolder();

            holder.txtTitle = (TextView) ret.findViewById(R.id.recommend_album_title);
            // 处理更多

            holder.txtMore = (TextView) ret.findViewById(R.id.recommend_album_more);
            // TODO 点击more 进入推荐列表

            holder.albumIcons = new ImageView[3];

            holder.albumNames = new TextView[3];
            holder.trackNames = new TextView[3];

            for (int i = 0; i < 3; i++) {
                // 给 holder 设置数组的内容
                holder.albumIcons[i] = (ImageView) findView(ret,"recommend_album_icon_"+i);
                // TODO 点击专辑图片 进入专辑详情
                holder.albumIcons[i].setOnClickListener(onRecommendAlbumClickListener);
                holder.albumNames[i] = (TextView) findView(ret,"recommend_album_name_"+i);
                holder.trackNames[i] = (TextView) findView(ret,"recommend_album_track_"+i);
            }
            ret.setTag(holder);
        }

        //3
        DiscoverRecommendAlbums albums = (DiscoverRecommendAlbums) items.get(position);
        String title = albums.getTitle();

        FileCache.newInstance(context);
        holder.txtTitle.setText(title);

        if (albums.isHasMore()){
            holder.txtMore.setVisibility(View.VISIBLE);
        }else{
            holder.txtMore.setVisibility(View.INVISIBLE);
        }



        List<AlbumRecommend> albumRecommends = albums.getAlbumRecommends();


        Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        for (int i = 0; i < holder.albumIcons.length; i++){

            holder.albumNames[i].setText(albumRecommends.get(i).getTitle());
            holder.trackNames[i].setText(albumRecommends.get(i).getTrackTitle());

//            ImageLoadTask imageLoadTask = new ImageLoadTask(context,holder.albumIcons[i],200,200);
//            AsyncDrawable drawable = new AsyncDrawable(context.getResources(),bitmap,imageLoadTask);
//            holder.albumIcons[i].setImageDrawable(drawable);
//            imageLoadTask.execute(albumRecommends.get(i).getCoverLarge());
            // 使用 picasso 加载图片

            ImageView imageView = holder.albumIcons[i];
            imageView.setTag(Constants.TAG_DISCOVER_RECOMMEND_ALBUM+position+":"+i);
            Picasso.with(context).load(albumRecommends.get(i).getCoverLarge()).into(imageView);

        }
        return ret;
    }

    private View bindColunmView(int position, View convertView,ViewGroup parent){
        View ret = null;

        if (convertView != null){
            ret = convertView;
        }else {
            LayoutInflater inflater = LayoutInflater.from(context);
            ret = inflater.inflate(R.layout.discover_recommend_columns_item,parent,false);
        }
        ColumnViewHolder holder = (ColumnViewHolder) ret.getTag();

        if (holder ==null){
            holder = new ColumnViewHolder();
            holder.txtSubtitles = new TextView[4];
            for (int i = 0; i < 4; i++) {
                holder.txtSubtitles[i] = (TextView) findView(ret,"discover_columns_"+i);
            }
            ret.setTag(holder);
        }

        DiscoverRecommendColumns discoverRecommendColumns = (DiscoverRecommendColumns) items.get(position);

        for (int i = 0; i < 4; i++) {
            holder.txtSubtitles[i].setText(discoverRecommendColumns.getDiscoverColumnses().get(i).getSubtitle());
        }

        return ret;
    }

    private View bindSpecialView(int position, View convertView,ViewGroup parent){
        View ret = null;
        if (convertView != null) {
            ret = convertView;
        }else {
            LayoutInflater inflater = LayoutInflater.from(context);
            ret = inflater.inflate(R.layout.discover_recommend_special_item,parent,false);
        }

        // 2
        SpecialViewHolder holder = (SpecialViewHolder) ret.getTag();

        if (holder == null){
            holder = new SpecialViewHolder();
            holder.txtTitle = (TextView) ret.findViewById(R.id.recommend_special_title);
            holder.txtMore = (TextView) ret.findViewById(R.id.recommend_special_more);
            holder.itemContainer = (LinearLayout) ret.findViewById(R.id.recommend_special_container);
            ret.setTag(holder);
        }

        // 3 获取数据
        DiscoverRecommendSpecial special = (DiscoverRecommendSpecial) items.get(position);

        holder.txtTitle.setText(special.getTitle());

        if (special.isHasMore()){
            holder.txtMore.setVisibility(View.VISIBLE);
        }else {
            holder.txtMore.setVisibility(View.INVISIBLE);
        }


        // 3.1 清空旧的 LinearLayout 的数据 在根据听单的 item 来添加
        holder.itemContainer.removeAllViews();
        List<SpecialItem> specialItems = special.getSpecialItems();
        if (specialItems != null) {

            int index = -1;
            int itemCount = specialItems.size();
            for (SpecialItem specialItem : specialItems) {
                index++;
                SpecialItemView itemView = new SpecialItemView(context);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                itemView.setLayoutParams(lp);
                holder.itemContainer.addView(itemView);

                // 设置听单的内容
                itemView.setTitle(specialItem.getTitle());
                itemView.setSubtitle(specialItem.getSubtitle());
                itemView.setNumber(specialItem.getFootnote());

                itemView.setShowBottomLine(true);

                // 判断是否时最后一个

                ImageView imageView = itemView.getImgIcon();
                String coverPath = specialItem.getCoverPath();
                Picasso.with(context).load(coverPath).into(imageView);

                if (index == itemCount - 1){
                    // 最后一个
                    itemView.setShowBottomLine(false);
                }
            }
        }


        return ret;
    }

    /**
     * 利用类的反射来获取指定的 R.id.xxx 代表的 View
     * @param container
     * @param fieldName
     * @return
     */
    public static View findView(View container,String fieldName){

        View ret = null;
        if (container != null && fieldName != null){
            Class<R.id> idClass = R.id.class;
            try {
                Field field = idClass.getDeclaredField(fieldName);
                int id = field.getInt(idClass);
                // 通过静态常量 获取整形 int 置来查找 View
                ret = container.findViewById(id);

            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                ;
            }
        }

        return ret;
    }


    private static class ColumnViewHolder{
        public TextView[] txtSubtitles;
    }
    /**
     * 精品听单 ViewHolder
     */
    private static class SpecialViewHolder{
        public TextView txtTitle;
        public TextView txtMore;

        // 存储 SpecialItemView
        public LinearLayout itemContainer;
    }

    /**
     * 小编推荐的 ViewHolder
     */
    private static class AlbumViewHolder{
        public TextView txtTitle;
        public TextView txtMore;

        public ImageView[] albumIcons; // 三张图片

        public TextView[] albumNames; // 三个专辑标题

        public TextView[] trackNames; // 三个曲目名称
    }

}
